﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;

public class LowResPositionSync : Photon.MonoBehaviour 
{	
	[HideInInspector]private PhotonView photView;
	public float acceptableError;
	public float syncPeriod = 1;
	void Awake()
	{	

		photView = PhotonView.Get(this);

		if (PhotonNetwork.inRoom)
		{
			NetworkStart();
		}
	}
	public virtual void OnJoinedRoom()
	{	
		NetworkStart();
	}
	void NetworkStart()
	{
		Debug.Log("joined Room -" + transform.gameObject.name);
		SyncPosition();
		if (PhotonNetwork.player == photView.owner)
		{
			BeginRecurrentPositionSync();
		}
		
	}

	void BeginRecurrentPositionSync()
	{
		StartCoroutine(SyncAfter(syncPeriod));
	}
	IEnumerator SyncAfter(float time)
	{
		yield return new WaitForSeconds(time);
		SendPosition();
		BeginRecurrentPositionSync();
	}
	void SyncPosition()
	{
		photView.RPC("SendPosition",PhotonTargets.All);
	}

	[PunRPC]
	public void SendPosition()
	{
		if (photView.isMine)
		{
			photView.RPC("SetPositionOnAllClients",PhotonTargets.All,transform.position,transform.rotation);
		}
		
	}

	[PunRPC]
	public void SetPositionOnAllClients(Vector3 position,Quaternion rotation,PhotonMessageInfo info)
	{
		if (info.sender != PhotonNetwork.player)
		{	
			if (GameFunctions.PlanarDistanceBetween(position,transform.position)>acceptableError)
			{
			transform.position = position;
			}
			transform.rotation = rotation;
		}
	}
}
